import { forwardRef, useImperativeHandle, useRef } from 'react'
import {
  Animated,
  GestureResponderEvent,
  Pressable,
  StyleSheet,
} from 'react-native'

interface VideoProgressProps {
  onPressProgress?: (event: GestureResponderEvent) => void
}
export interface VideoProgressDom {
  changeCrnPrgWdt: (num: number, type: 'crn' | 'ply') => void
}
export default forwardRef(function VideoProgress(
  props: VideoProgressProps,
  ref,
) {
  const crnWidth = useRef(new Animated.Value(0)).current // 当前播放进度的动画
  const plyWidth = useRef(new Animated.Value(0)).current // 已下载的可播放的进度的动画
  useImperativeHandle(
    ref,
    () => ({
      changeCrnPrgWdt(num: number, type: 'crn' | 'ply' = 'crn') {
        Animated.timing(type === 'crn' ? crnWidth : plyWidth, {
          toValue: num,
          useNativeDriver: false,
          duration: 200,
        }).start()
      },
    }),
    [],
  )

  return (
    <Pressable style={style.progressWrap} onPress={props.onPressProgress}>
      <Animated.View
        style={[
          style.progress,
          style.progressCurrent,
          {
            transform: [{ translateX: crnWidth }],
          },
        ]}
      />
      <Animated.View
        style={[
          style.progress,
          style.progressPlayable,
          {
            transform: [{ translateX: plyWidth }],
          },
        ]}
      />
    </Pressable>
  )
})

const style = StyleSheet.create({
  progressWrap: {
    height: 8,
    width: '100%',
    zIndex: 10,
    position: 'relative',
  },
  progress: {
    position: 'absolute',
    bottom: 3,
    height: 2,
    width: '100%',
    left: '-100%',
  },
  progressCurrent: {
    backgroundColor: '#666',
    zIndex: 2,
  },
  progressPlayable: {
    backgroundColor: '#313131',
  },
})
